package main

import (
	"bufio"
	"crypto/aes"
	"crypto/cipher"
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
)

// 定义执行命令行函数，返回执行结果和结果数据
func ExecCommand(CommandName string, params ...string) (CMDRes bool, ResData []string) {
	ResData = make([]string, 1, 1)
	cmd := exec.Command(CommandName, params...)
	//fmt.Println(cmd.Args)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return false, ResData
	}

	if err := cmd.Start(); err != nil {
		return false, ResData
	}

	reader := bufio.NewReader(stdout)

	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		//fmt.Println(line)
		ResData = append(ResData, line)
	}

	if err := cmd.Wait(); err != nil {
		return false, ResData
	}
	return true, ResData
}

//返回一个32位md5加密后的字符串
func GetMD5Encode(data string) string {
	h := md5.New()
	h.Write([]byte(data))
	// 定制化生成的盐
	return hex.EncodeToString(h.Sum(nil))
}

//返回一个16位md5加密后的字符串
func Get16MD5Encode(data string) string {
	return GetMD5Encode(data)[8:24]
}

// Decrypt from base64 to decrypted string
func AESDecrypt(key []byte, cryptoText string) (string, bool) {
	ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", false
	}

	if len(ciphertext) < aes.BlockSize {
		return "", false
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)

	stream.XORKeyStream(ciphertext, ciphertext)

	return fmt.Sprintf("%s", ciphertext), true
}

func CreateUpdateFile(info string, FilePath string) {
	f, err := os.Create(FilePath)
	defer f.Close()
	if err != nil {
		log.Fatal("license failed")
	}
	w := bufio.NewWriter(f)
	if _, err := w.WriteString(info); err != nil {
		log.Fatal("license failed")
	}
	w.Flush()
}

// 判断文件是否存在  存在返回 true 不存在返回false
/*
	cfcyrcw
	cqxzjyb
	jzdkmry
	yrsxlqc
*/
func CheckFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

func GenerateAESTime(text string) string {
	//fmt.Println("THE KEY is", key)
	text, ok := AESEncrypt(key, text)
	//fmt.Println(text)
	if !ok {
		log.Fatal("time encrypt is failed")
	}
	return text
}

//计算文件MD5
func CalcFileMD5(filename string) (string, error) {
	f, err := os.Open(filename) //打开文件
	if nil != err {
		//fmt.Println(err)
		return "", err
	}
	defer f.Close()

	md5Handle := md5.New()         //创建 md5 句柄
	_, err = io.Copy(md5Handle, f) //将文件内容拷贝到 md5 句柄中
	if nil != err {
		//fmt.Println(err)
		return "", err
	}
	md := md5Handle.Sum(nil)        //计算 MD5 值，返回 []byte
	md5str := fmt.Sprintf("%x", md) //将 []byte 转为 string
	return md5str, nil
}

func AppendFile(filename string, str_content string) {
	//fmt.Println("in appendFile")
	fd, _ := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	fd_time := time.Now().Format("2006-01-02 15:04:05")
	fd_content := strings.Join([]string{"======", fd_time, "=====", str_content, "\n"}, "")
	buf := []byte(fd_content)
	fd.Write(buf)
	fd.Close()
}

func DeleteStringSth(s string, sth []string, count int) string {
	if count <= 0 {
		count = -1
	}
	for i, v := range sth {
		s = strings.Replace(s, v, "", -1)
		fmt.Println(i)
	}
	return s
}

func ReadFile(dir string) string {
	f, err := ioutil.ReadFile(dir)
	if err != nil {
		fmt.Println("read fail", err)
		//log.Fatal("verify failed")
	}
	return string(f)
}
